import { getStore, setStore } from "@/utils/store.js";
const state = {
  followerList: getStore("followerList") || [],
};
const mutations = {
  SET_FOLLOWER_LIST: (state, followerList) => {
    state.followerList = followerList;
    setStore("followerList", followerList);
  },
};
const actions = {
  removeFollower({ commit, state }, followerId) {
    return new Promise((reslove, reject) => {
      if (this.getters.accountId) {
        const list = state.followerList;
        if (
          list.find((item) => {
            return item.accountId === this.getters.accountId;
          })
        ) {
          const index = list.findIndex((item) => {
            return item.accountId === this.getters.accountId;
          });
          if (list[index].followers.includes(followerId)) {
            const followers = list[index].followers.filter(item =>{
              return item != followerId
            })
            list[index].followers = followers
            commit("SET_FOLLOWER_LIST", list);
            reslove("取关成功!");
          } else {
            reject("未关注过!");
          }
        } else {
          list.push({
            accountId: this.getters.accountId,
            followers: [followerId],
          });
          commit("SET_FOLLOWER_LIST", list);
        }
      } else {
        reject("请先登录!");
      }
    });
  },
  addFollower({ commit, state }, followerId) {
    return new Promise((reslove, reject) => {
      if (this.getters.accountId) {
        const list = state.followerList;
        if (
          list.find((item) => {
            return item.accountId === this.getters.accountId;
          })
        ) {
          const index = list.findIndex((item) => {
            return item.accountId === this.getters.accountId;
          });
          if (list[index].followers.includes(followerId)) {
            reject("已关注过!");
          } else {
            list[index].followers.push(followerId);
            commit("SET_FOLLOWER_LIST", list);
            reslove("关注成功!");
          }
        } else {
          list.push({
            accountId: this.getters.accountId,
            followers: [followerId],
          });
          commit("SET_FOLLOWER_LIST", list);
        }
      } else {
        reject("请先登录!");
      }
    });
  },
};

export default { state, mutations, actions };
